package com.lr.falsework.common.tool;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;


/**
 * AES Encrypt
 * 
 * @author ewang35
 *
 */
public class CipherUtils {

	private static byte[] key = { 0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41,
			0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79 };// "thisIsASecretKey";
	static {
		// try {
		// key = PropertiesUtil.getString("secret.key").getBytes("UTF-8");
		// } catch (UnsupportedEncodingException e) {
		// LOGGER.error("Error in parsing secret.key", e);
		// }
	}

	/**
	 * 加密函数.
	 * 
	 * @param strToEncrypt
	 * @return
	 */
	public static String encrypt(String strToEncrypt) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			final byte[] encryptedString = Base64.encodeBase64(cipher
					.doFinal(strToEncrypt.getBytes()));
			return new String(encryptedString, "UTF-8");
		} catch (Exception e) {
		}
		return null;

	}

	/**
	 * 解密函数.
	 * 
	 * @param strToDecrypt
	 * @return
	 */
	public static String decrypt(String strToDecrypt) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			final String decryptedString = new String(cipher.doFinal(Base64
					.decodeBase64(strToDecrypt.getBytes("UTF-8"))));
			return decryptedString;
		} catch (Exception e) {

		}
		return null;
	}

}
